const http = require('http')
const  moment = require('moment')
const colors = require('colors');
colors.enable();
const {spawn} = require('child_process')
const createHandler = require('gitee-webhook-handler')

const shellScriptsPath = {
    testServer: './deploy-test-server.sh',
    testClient: './deploy-test-client.sh',
    testDocker: './deploy-test-docker.sh',
    testClientMerchant:'./deploy-test-client-merchants.sh',
}

const nowString=()=>moment().utcOffset('+0800').format('YYYY-MM-DD HH:mm:ss.SSS');

// Deploy 测试服务器Laradock 代码 push 到master 分支后 自动构建
const testDockerHandler = createHandler({path: '/web-hook', secret: '123456'})
testDockerHandler.on('error', err => {
    console.error(colors.red(`Error: ${err.message}`))
})
// 监听到push事件的时候执行我们的自动化脚本
testDockerHandler.on('Push Hook', event => {
    console.log(colors.green.bold(`Received a push event from ${event.payload.repository.name} to ${event.payload.ref}`))
    // console.log(event.payload)
    // push请求且为master执行shell脚本
    if (event.payload.ref === 'refs/heads/master' && event.payload.repository.name==='laradock'){
        console.log(colors.green.bold(`###################CI/CD start ${nowString()} ###################`))
        runCommand('sh', [shellScriptsPath.testDocker], console.log)
    }
    if (event.payload.ref === 'refs/heads/master' && event.payload.repository.name==='commerce-server'){
        console.log(colors.green.bold(`###################CI/CD start ${nowString()} ###################`))
        runCommand('sh', [shellScriptsPath.testServer], console.log)
    }
    if (event.payload.ref === 'refs/heads/master' && event.payload.repository.name==='vue-admin'){
        console.log(colors.green.bold(`###################CI/CD start ${nowString()} ###################`))
        runCommand('sh', [shellScriptsPath.testClient], console.log)
    }

    if (event.payload.ref === 'refs/heads/master' && event.payload.repository.name==='commerce-merchant'){
        console.log(colors.green.bold(`###################CI/CD start ${nowString()} ###################`))
        runCommand('sh', [shellScriptsPath.testClientMerchant], console.log)
    }

})


const PORT = 9005
http.createServer((req, res) => {
    testDockerHandler(req, res, () => {
        res.statusCode = 404
        res.end('No such location')
    })
})
    .listen(PORT)

function runCommand(cmd, args, callback) {
    let response = ''
    const child = spawn(cmd, args)
    // and unref() somehow disentangles the child's event loop from the parent's:
    child.unref();
    child.stdout.on('data', buffer => {
        console.log(buffer.toString())
        response += buffer.toString()
    })
    child.stdout.on('end', () => {
        callback(response)
        console.log(colors.green.bold(`###################CI/CD end ${nowString()} ###################`))
    })
}
